/*
 * personas.java
 *
 * Created on 09-oct-2008, 14:27:33
 */
package investigaciones_itm.Personas;

import com.sun.rave.faces.data.DefaultSelectItemsArray;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.webui.jsf.component.AddRemove;
import com.sun.webui.jsf.component.Body;
import com.sun.webui.jsf.component.Button;
import com.sun.webui.jsf.component.Calendar;
import com.sun.webui.jsf.component.DropDown;
import com.sun.webui.jsf.component.Form;
import com.sun.webui.jsf.component.Head;
import com.sun.webui.jsf.component.Html;
import com.sun.webui.jsf.component.Label;
import com.sun.webui.jsf.component.Link;
import com.sun.webui.jsf.component.Page;
import com.sun.webui.jsf.component.PanelGroup;
import com.sun.webui.jsf.component.PanelLayout;
import com.sun.webui.jsf.component.PasswordField;
import com.sun.webui.jsf.component.Tab;
import com.sun.webui.jsf.component.TabSet;
import com.sun.webui.jsf.component.TextField;
import com.sun.webui.jsf.model.Option;
import com.sun.webui.jsf.model.SingleSelectOptionsList;
import javax.faces.FacesException;
import investigaciones_itm.ApplicationBean1;
import investigaciones_itm.SessionBean1;
import investigaciones_itm.RequestBean1;
import itm.bo.personas.PersonasBO;
import itm.exception.ControlException;
import itm.vo.administracion.InstitucionVO;
import itm.vo.administracion.OcupacionesVO;
import itm.vo.administracion.RolVo;
import itm.vo.administracion.TipoIdentificacionVO;
import itm.vo.administracion.facultadesVO;
import itm.vo.personas.PersonaOcupacionVO;
import itm.vo.personas.PersonaVO;
import javax.faces.component.UISelectItems;
import javax.faces.component.html.HtmlMessages;
import javax.faces.component.html.HtmlPanelGrid;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.component.html.HtmlSelectOneListbox;
import javax.faces.validator.DoubleRangeValidator;
import javax.faces.model.SelectItem;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @author Administrador
 */
public class crearPersona extends AbstractPageBean {

    private TipoIdentificacionVO tipoIdVO = new TipoIdentificacionVO();
    private PersonaVO personaVO = new PersonaVO();
    private PersonasBO personaBO = new PersonasBO();
    private OcupacionesVO ocupacionVO = new OcupacionesVO();
    private InstitucionVO institucionVO = new InstitucionVO();
    private facultadesVO facultadVO = new facultadesVO();
    private RolVo rolVO = new RolVo();
    private PersonaOcupacionVO perOcupacionVO = new PersonaOcupacionVO();
    private List<TipoIdentificacionVO> listaTipoId = new ArrayList<TipoIdentificacionVO>();
    private List<OcupacionesVO> listaOcupacion = new ArrayList<OcupacionesVO>();
    private List<InstitucionVO> listaInstitucion = new ArrayList<InstitucionVO>();
    private List<facultadesVO> listaFacultad = new ArrayList<facultadesVO>();

    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">
    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
        dropListTipoIdDefaultOptions.setOptions(new com.sun.webui.jsf.model.Option[]{new com.sun.webui.jsf.model.Option("item1", "Cedula CiudadanÃ­a"), new com.sun.webui.jsf.model.Option("item2", "Cedula ExtranjerÃ­a"), new com.sun.webui.jsf.model.Option("item3", "Tarjeta de Identidad")});
        listaEstadoDefaultOptions.setOptions(new com.sun.webui.jsf.model.Option[]{new com.sun.webui.jsf.model.Option("Activo", "Activo"), new com.sun.webui.jsf.model.Option("Inactivo", "Inactivo")});
        addRemoveList1.setWidth("383");

    }
    private Page page1 = new Page();

    public Page getPage1() {
        return page1;
    }

    public void setPage1(Page p) {
        this.page1 = p;
    }
    private Html html1 = new Html();

    public Html getHtml1() {
        return html1;
    }

    public void setHtml1(Html h) {
        this.html1 = h;
    }
    private Head head1 = new Head();

    public Head getHead1() {
        return head1;
    }

    public void setHead1(Head h) {
        this.head1 = h;
    }
    private Link link1 = new Link();

    public Link getLink1() {
        return link1;
    }

    public void setLink1(Link l) {
        this.link1 = l;
    }
    private Body body1 = new Body();

    public Body getBody1() {
        return body1;
    }

    public void setBody1(Body b) {
        this.body1 = b;
    }
    private Form form1 = new Form();

    public Form getForm1() {
        return form1;
    }

    public void setForm1(Form f) {
        this.form1 = f;
    }
    private PanelGroup groupPanel1 = new PanelGroup();

    public PanelGroup getGroupPanel1() {
        return groupPanel1;
    }

    public void setGroupPanel1(PanelGroup pg) {
        this.groupPanel1 = pg;
    }
    private TabSet tabSet1 = new TabSet();

    public TabSet getTabSet1() {
        return tabSet1;
    }

    public void setTabSet1(TabSet ts) {
        this.tabSet1 = ts;
    }
    private Tab tab1 = new Tab();

    public Tab getTab1() {
        return tab1;
    }

    public void setTab1(Tab t) {
        this.tab1 = t;
    }
    private PanelLayout layoutPanel1 = new PanelLayout();

    public PanelLayout getLayoutPanel1() {
        return layoutPanel1;
    }

    public void setLayoutPanel1(PanelLayout pl) {
        this.layoutPanel1 = pl;
    }
    private Label label2 = new Label();

    public Label getLabel2() {
        return label2;
    }

    public void setLabel2(Label l) {
        this.label2 = l;
    }
    private Label label17 = new Label();

    public Label getLabel17() {
        return label17;
    }

    public void setLabel17(Label l) {
        this.label17 = l;
    }
    private Label label18 = new Label();

    public Label getLabel18() {
        return label18;
    }

    public void setLabel18(Label l) {
        this.label18 = l;
    }
    private Label label19 = new Label();

    public Label getLabel19() {
        return label19;
    }

    public void setLabel19(Label l) {
        this.label19 = l;
    }
    private Label label20 = new Label();

    public Label getLabel20() {
        return label20;
    }

    public void setLabel20(Label l) {
        this.label20 = l;
    }
    private Label label21 = new Label();

    public Label getLabel21() {
        return label21;
    }

    public void setLabel21(Label l) {
        this.label21 = l;
    }
    private Label label22 = new Label();

    public Label getLabel22() {
        return label22;
    }

    public void setLabel22(Label l) {
        this.label22 = l;
    }
    private Label label23 = new Label();

    public Label getLabel23() {
        return label23;
    }

    public void setLabel23(Label l) {
        this.label23 = l;
    }
    private Label label24 = new Label();

    public Label getLabel24() {
        return label24;
    }

    public void setLabel24(Label l) {
        this.label24 = l;
    }
    private Label label25 = new Label();

    public Label getLabel25() {
        return label25;
    }

    public void setLabel25(Label l) {
        this.label25 = l;
    }
    private Label label26 = new Label();

    public Label getLabel26() {
        return label26;
    }

    public void setLabel26(Label l) {
        this.label26 = l;
    }
    private Label label27 = new Label();

    public Label getLabel27() {
        return label27;
    }

    public void setLabel27(Label l) {
        this.label27 = l;
    }
    private Label label28 = new Label();

    public Label getLabel28() {
        return label28;
    }

    public void setLabel28(Label l) {
        this.label28 = l;
    }
    private Label label29 = new Label();

    public Label getLabel29() {
        return label29;
    }

    public void setLabel29(Label l) {
        this.label29 = l;
    }
    private TextField campoNombrePersona = new TextField();

    public TextField getCampoNombrePersona() {
        return campoNombrePersona;
    }

    public void setCampoNombrePersona(TextField tf) {
        this.campoNombrePersona = tf;
    }
    private Calendar fechaNacimiento = new Calendar();

    public Calendar getFechaNacimiento() {
        return fechaNacimiento;
    }

    public void setFechaNacimiento(Calendar c) {
        this.fechaNacimiento = c;
    }
    private TextField campoTelPersona = new TextField();

    public TextField getCampoTelPersona() {
        return campoTelPersona;
    }

    public void setCampoTelPersona(TextField tf) {
        this.campoTelPersona = tf;
    }
    private Calendar fechaIngresoPersona = new Calendar();

    public Calendar getFechaIngresoPersona() {
        return fechaIngresoPersona;
    }

    public void setFechaIngresoPersona(Calendar c) {
        this.fechaIngresoPersona = c;
    }
    private TextField campoEmail = new TextField();

    public TextField getCampoEmail() {
        return campoEmail;
    }

    public void setCampoEmail(TextField tf) {
        this.campoEmail = tf;
    }
    private TextField campoUsr = new TextField();

    public TextField getCampoUsr() {
        return campoUsr;
    }

    public void setCampoUsr(TextField tf) {
        this.campoUsr = tf;
    }
    private Button buttonGuardarPersona = new Button();

    public Button getButtonGuardarPersona() {
        return buttonGuardarPersona;
    }

    public void setButtonGuardarPersona(Button b) {
        this.buttonGuardarPersona = b;
    }
    private Button buttonCancelarPersona = new Button();

    public Button getButtonCancelarPersona() {
        return buttonCancelarPersona;
    }

    public void setButtonCancelarPersona(Button b) {
        this.buttonCancelarPersona = b;
    }
    private Label label1 = new Label();

    public Label getLabel1() {
        return label1;
    }

    public void setLabel1(Label l) {
        this.label1 = l;
    }
    private SingleSelectOptionsList dropListTipoIdDefaultOptions = new SingleSelectOptionsList();

    public SingleSelectOptionsList getDropListTipoIdDefaultOptions() {
        return dropListTipoIdDefaultOptions;
    }

    public void setDropListTipoIdDefaultOptions(SingleSelectOptionsList ssol) {
        this.dropListTipoIdDefaultOptions = ssol;
    }
    private TextField campoIdentificacion = new TextField();

    public TextField getCampoIdentificacion() {
        return campoIdentificacion;
    }

    public void setCampoIdentificacion(TextField tf) {
        this.campoIdentificacion = tf;
    }
    private DropDown listaEstado = new DropDown();

    public DropDown getListaEstado() {
        return listaEstado;
    }

    public void setListaEstado(DropDown dd) {
        this.listaEstado = dd;
    }
    private SingleSelectOptionsList listaEstadoDefaultOptions = new SingleSelectOptionsList();

    public SingleSelectOptionsList getListaEstadoDefaultOptions() {
        return listaEstadoDefaultOptions;
    }

    public void setListaEstadoDefaultOptions(SingleSelectOptionsList ssol) {
        this.listaEstadoDefaultOptions = ssol;
    }
    private DoubleRangeValidator doubleRangeValidator1 = new DoubleRangeValidator();

    public DoubleRangeValidator getDoubleRangeValidator1() {
        return doubleRangeValidator1;
    }

    public void setDoubleRangeValidator1(DoubleRangeValidator drv) {
        this.doubleRangeValidator1 = drv;
    }
    private HtmlSelectOneListbox listboxTipoId = new HtmlSelectOneListbox();

    public HtmlSelectOneListbox getListboxTipoId() {

        listboxTipoId = new HtmlSelectOneListbox();

        tipoIdVO = new TipoIdentificacionVO();
        personaBO = new PersonasBO();
        listaTipoId = new ArrayList<TipoIdentificacionVO>();
        String idTipoId = "";
        String tipoID = "";
        List collection = new ArrayList();

        try {

            listaTipoId = personaBO.llenarListaTipoId();

            for (int i = 0; i < listaTipoId.size(); i++) {

                idTipoId = listaTipoId.get(i).getIdTipoId();
                tipoID = listaTipoId.get(i).getTipo();
                collection.add(new SelectItem(idTipoId, tipoID));
            }

            UISelectItems comboTipo = new UISelectItems();
            comboTipo.setValue(collection);
            listboxTipoId.getChildren().add(comboTipo);

        } catch (Exception e) {
            e.getStackTrace();
        }

        return listboxTipoId;
    }

    public void setListboxTipoId(HtmlSelectOneListbox hsol) {
        this.listboxTipoId = hsol;
    }
    private UISelectItems listbox2SelectItems = new UISelectItems();

    public UISelectItems getListbox2SelectItems() {
        return listbox2SelectItems;
    }

    public void setListbox2SelectItems(UISelectItems uisi) {
        this.listbox2SelectItems = uisi;
    }
    private HtmlSelectOneListbox listboxOcupaciones = new HtmlSelectOneListbox();

    public HtmlSelectOneListbox getListboxOcupaciones() {

        listboxOcupaciones = new HtmlSelectOneListbox();

        //tipoIdVO = new TipoIdentificacionVO();
        ocupacionVO = new OcupacionesVO();
        personaBO = new PersonasBO();
        //listaTipoId = new ArrayList<TipoIdentificacionVO>();
        listaOcupacion = new ArrayList<OcupacionesVO>();
        //String idTipoId = "";
        //String tipoID = "";
        String idOcupacion = "";
        String ocupacion = "";
        List collection = new ArrayList();

        try {

            listaOcupacion = personaBO.llenarListaOcupacion();

            for (int i = 0; i < listaOcupacion.size(); i++) {

                idOcupacion = listaOcupacion.get(i).getIdOcupacion();
                ocupacion = listaOcupacion.get(i).getNombreOcupacion();
                collection.add(new SelectItem(idOcupacion, ocupacion));
            }

            UISelectItems comboOcupacion = new UISelectItems();
            comboOcupacion.setValue(collection);
            listboxOcupaciones.getChildren().add(comboOcupacion);

        } catch (Exception e) {
            e.getStackTrace();
        }

        return listboxOcupaciones;
    }

    public void setListboxOcupaciones(HtmlSelectOneListbox hsol) {
        this.listboxOcupaciones = hsol;
    }
    private DefaultSelectItemsArray listbox2DefaultItems1 = new DefaultSelectItemsArray();

    public DefaultSelectItemsArray getListbox2DefaultItems1() {
        return listbox2DefaultItems1;
    }

    public void setListbox2DefaultItems1(DefaultSelectItemsArray dsia) {
        this.listbox2DefaultItems1 = dsia;
    }
    private UISelectItems listbox2SelectItems1 = new UISelectItems();

    public UISelectItems getListbox2SelectItems1() {
        return listbox2SelectItems1;
    }

    public void setListbox2SelectItems1(UISelectItems uisi) {
        this.listbox2SelectItems1 = uisi;
    }
    private DefaultSelectItemsArray listboxTipoIdDefaultItems = new DefaultSelectItemsArray();

    public DefaultSelectItemsArray getListboxTipoIdDefaultItems() {
        return listboxTipoIdDefaultItems;
    }

    public void setListboxTipoIdDefaultItems(DefaultSelectItemsArray dsia) {
        this.listboxTipoIdDefaultItems = dsia;
    }
    private DefaultSelectItemsArray listbox2DefaultItems2 = new DefaultSelectItemsArray();

    public DefaultSelectItemsArray getListbox2DefaultItems2() {
        return listbox2DefaultItems2;
    }

    public void setListbox2DefaultItems2(DefaultSelectItemsArray dsia) {
        this.listbox2DefaultItems2 = dsia;
    }
    private DefaultSelectItemsArray listbox2DefaultItems3 = new DefaultSelectItemsArray();

    public DefaultSelectItemsArray getListbox2DefaultItems3() {
        return listbox2DefaultItems3;
    }

    public void setListbox2DefaultItems3(DefaultSelectItemsArray dsia) {
        this.listbox2DefaultItems3 = dsia;
    }
    private HtmlSelectOneListbox listboxInstituciones = new HtmlSelectOneListbox();

    public HtmlSelectOneListbox getListboxInstituciones() {

        listboxInstituciones = new HtmlSelectOneListbox();

        //tipoIdVO = new TipoIdentificacionVO();
        institucionVO = new InstitucionVO();
        personaBO = new PersonasBO();
        //listaTipoId = new ArrayList<TipoIdentificacionVO>();
        listaInstitucion = new ArrayList<InstitucionVO>();
        //String idTipoId = "";
        //String tipoID = "";
        String idInstitucion = "";
        String institucion = "";
        List collection = new ArrayList();

        try {

            listaInstitucion = personaBO.llenarListaInstitucion();

            for (int i = 0; i < listaInstitucion.size(); i++) {

                idInstitucion = listaInstitucion.get(i).getIdInstitucion();
                institucion = listaInstitucion.get(i).getNombreInstitucion();
                collection.add(new SelectItem(idInstitucion, institucion));
            }

            UISelectItems comboInstitucion = new UISelectItems();
            comboInstitucion.setValue(collection);
            listboxInstituciones.getChildren().add(comboInstitucion);

        } catch (Exception e) {
            e.getStackTrace();
        }

        return listboxInstituciones;
    }

    public void setListboxInstituciones(HtmlSelectOneListbox hsol) {
        this.listboxInstituciones = hsol;
    }
    private UISelectItems listbox1SelectItems = new UISelectItems();

    public UISelectItems getListbox1SelectItems() {
        return listbox1SelectItems;
    }

    public void setListbox1SelectItems(UISelectItems uisi) {
        this.listbox1SelectItems = uisi;
    }
    private HtmlSelectOneListbox listboxFacultad = new HtmlSelectOneListbox();

    public HtmlSelectOneListbox getListboxFacultad() {

        listboxFacultad = new HtmlSelectOneListbox();

        //tipoIdVO = new TipoIdentificacionVO();
        facultadVO = new facultadesVO();
        personaBO = new PersonasBO();
        //listaTipoId = new ArrayList<TipoIdentificacionVO>();
        listaFacultad = new ArrayList<facultadesVO>();
        //String idTipoId = "";
        //String tipoID = "";
        String idFacultad = "";
        String facultad = "";
        List collection = new ArrayList();

        try {

            listaFacultad = personaBO.llenarListaFacultades();

            for (int i = 0; i < listaFacultad.size(); i++) {

                idFacultad = listaFacultad.get(i).getIdFacultad();
                facultad = listaFacultad.get(i).getNombreFacultad();
                collection.add(new SelectItem(idFacultad, facultad));
            }

            UISelectItems comboFacultad = new UISelectItems();
            comboFacultad.setValue(collection);
            listboxFacultad.getChildren().add(comboFacultad);

        } catch (Exception e) {
            e.getStackTrace();
        }

        return listboxFacultad;
    }

    public void setListboxFacultad(HtmlSelectOneListbox hsol) {
        this.listboxFacultad = hsol;
    }
    private DefaultSelectItemsArray listbox1DefaultItems1 = new DefaultSelectItemsArray();

    public DefaultSelectItemsArray getListbox1DefaultItems1() {
        return listbox1DefaultItems1;
    }

    public void setListbox1DefaultItems1(DefaultSelectItemsArray dsia) {
        this.listbox1DefaultItems1 = dsia;
    }
    private UISelectItems listbox1SelectItems1 = new UISelectItems();

    public UISelectItems getListbox1SelectItems1() {
        return listbox1SelectItems1;
    }

    public void setListbox1SelectItems1(UISelectItems uisi) {
        this.listbox1SelectItems1 = uisi;
    }
    private DefaultSelectItemsArray listboxInstitucionesDefaultItems = new DefaultSelectItemsArray();

    public DefaultSelectItemsArray getListboxInstitucionesDefaultItems() {
        return listboxInstitucionesDefaultItems;
    }

    public void setListboxInstitucionesDefaultItems(DefaultSelectItemsArray dsia) {
        this.listboxInstitucionesDefaultItems = dsia;
    }
    private DefaultSelectItemsArray listbox1DefaultItems2 = new DefaultSelectItemsArray();

    public DefaultSelectItemsArray getListbox1DefaultItems2() {
        return listbox1DefaultItems2;
    }

    public void setListbox1DefaultItems2(DefaultSelectItemsArray dsia) {
        this.listbox1DefaultItems2 = dsia;
    }
    private DefaultSelectItemsArray listbox1DefaultItems3 = new DefaultSelectItemsArray();

    public DefaultSelectItemsArray getListbox1DefaultItems3() {
        return listbox1DefaultItems3;
    }

    public void setListbox1DefaultItems3(DefaultSelectItemsArray dsia) {
        this.listbox1DefaultItems3 = dsia;
    }
    private DefaultSelectItemsArray listbox1DefaultItems = new DefaultSelectItemsArray();

    public DefaultSelectItemsArray getListbox1DefaultItems() {
        return listbox1DefaultItems;
    }

    public void setListbox1DefaultItems(DefaultSelectItemsArray dsia) {
        this.listbox1DefaultItems = dsia;
    }
    private UISelectItems listbox1SelectItems2 = new UISelectItems();

    public UISelectItems getListbox1SelectItems2() {
        return listbox1SelectItems2;
    }

    public void setListbox1SelectItems2(UISelectItems uisi) {
        this.listbox1SelectItems2 = uisi;
    }
    private PasswordField campoContraseña = new PasswordField();

    public PasswordField getCampoContraseña() {
        return campoContraseña;
    }

    public void setCampoContraseña(PasswordField pf) {
        this.campoContraseña = pf;
    }
    private PasswordField campoReContraseña = new PasswordField();

    public PasswordField getCampoReContraseña() {
        return campoReContraseña;
    }

    public void setCampoReContraseña(PasswordField pf) {
        this.campoReContraseña = pf;
    }
    private Button button1 = new Button();

    public Button getButton1() {
        return button1;
    }

    public void setButton1(Button b) {
        this.button1 = b;
    }
    private HtmlMessages messageList1 = new HtmlMessages();

    public HtmlMessages getMessageList1() {
        return messageList1;
    }

    public void setMessageList1(HtmlMessages hm) {
        this.messageList1 = hm;
    }
    private HtmlPanelGrid gridPanelBotones = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanelBotones() {
        return gridPanelBotones;
    }

    public void setGridPanelBotones(HtmlPanelGrid hpg) {
        this.gridPanelBotones = hpg;
    }
    private AddRemove addRemoveList1 = new AddRemove();

    public AddRemove getAddRemoveList1() {
        return addRemoveList1;
    }

    public void setAddRemoveList1(AddRemove ar) {
        this.addRemoveList1 = ar;
    }

    /** Holds value of property availableOptions. */
    private Option[] availableOptions = null;
    /** Holds value of property selectedOptions. */
    private String[] selectedOptions = null;

    public Option[] getAvailableOptions() {
        return availableOptions;
    }

    public void setAvailableOptions(Option[] availableOptions) {
        this.availableOptions = availableOptions;
    }

    public String[] getSelectedOptions() {
        return selectedOptions;
    }

    public void setSelectedOptions(String[] selectedOptions) {
        this.selectedOptions = selectedOptions;
    }

    // </editor-fold>
    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public crearPersona() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {

        super.init();

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("personas Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }

    // </editor-fold>
    // Perform application initialization that must complete
    // *after* managed components are initialized
    // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {

        rolVO = new RolVo();
        personaBO = new PersonasBO();
        List<RolVo> listaRolesDisponibles = new ArrayList<RolVo>();
        String idRol="";
        String nombreRol="";

        try {
            listaRolesDisponibles = personaBO.llenarListaRoles();
            Option[] opcion = new Option[listaRolesDisponibles.size()];

            for (int i = 0; i < listaRolesDisponibles.size(); i++) {
                idRol = listaRolesDisponibles.get(i).getIdRol();
                nombreRol = listaRolesDisponibles.get(i).getNombreRol();
                opcion[i] = new Option(idRol, nombreRol);
            } // end for
            availableOptions = opcion;
        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    public String tab1_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String buttonGuardarPersona_action() throws ControlException {

        String errorM = "";

        String tipoId = "";
        String id = "";
        String nombre = "";
        Date fechaN = null;
        String telefono = "";
        String email = "";
        String ocupacion = "";
        String institucion = "";
        String facultad = "";
        Date fechaIngreso = null;
        String estado = "";
        String usuario = "";
        String contrasenia = "";
        String reContrasenia = "";

        try {

            perOcupacionVO = new PersonaOcupacionVO();
            //perRolVO = new PersonaRolVO();
            personaVO = new PersonaVO();
            personaBO = new PersonasBO();

            java.util.Date fechaCalendario = (java.util.Date) fechaNacimiento.getValue();
            java.util.Date fechaCalendario2 = (java.util.Date) fechaIngresoPersona.getValue();

            tipoId = (String) listboxTipoId.getValue();
            id = (String) campoIdentificacion.getValue();
            nombre = (String) campoNombrePersona.getValue();
            telefono = (String) campoTelPersona.getValue();
            email = (String) campoEmail.getValue();
            ocupacion = (String) listboxOcupaciones.getValue();
            institucion = (String) listboxInstituciones.getValue();
            facultad = (String) listboxFacultad.getValue();
            estado = (String) listaEstado.getValue();
            usuario = (String) campoUsr.getValue();
            contrasenia = (String) campoContraseña.getValue();
            reContrasenia = (String) campoReContraseña.getValue();

            if(id == null || id.length() == 0 || id.equals("")){
                error("El número de indentificación es requerido");
                return null;
            }else{
                if(!esNumericoRegex(id)){
                    error("El número de identificación solo permite números");
                    return null;
                }
            }

            if(nombre == null || nombre.length()==0||nombre.equals("")){
                error("El nombre es requerido");
                return null;
            }else{
                if(!esCadenaRegex(nombre)){
                    error("El nombre contiene caracteres no validos");
                    return null;
                }
            }

            if(telefono == null|| telefono.length()==0||telefono.equals("")){
                error("El teléfono es requerido");
                return null;
            }else{
                if(!esNumericoRegex(telefono)){
                    error("No es un número de teléfono valido");
                    return null;
                }
            }

            if(email==null || email.length()==0||email.equals("")){
                error("El E-Mail es requerido");
                return null;
            }else{
                if(!validarCorreoRegex(email)){
                error("No es un E-Mail valido");
                return null;
                }
            }

            if(fechaCalendario==null){
                error("La fecha de Nacimiento es requerida");
                return null;
            }

            if(fechaCalendario2==null){
                error("La fecha de ingreso es requerida");
                return null;
            }

            if (selectedOptions == null ) {
                error("Por favor seleccione al menos un Rol");
                return null;
            }

            if(usuario==null || usuario.length()==0||usuario.equals("")){
                error("El usuario es requerido");
                return null;
            }

            if(contrasenia==null||contrasenia.length()==0||contrasenia.equals("")){
                error("La contraseña es requerida");
                return null;
            }

            if(reContrasenia==null || reContrasenia.length()==0||reContrasenia.equals("")){
                error("Por favor confirme la contraseña");
                return null;
            }
            


            fechaN = new Date(fechaCalendario.getTime());
            fechaIngreso = new Date(fechaCalendario2.getTime());

            personaVO.setIdTipoIdentificacion(tipoId);
            personaVO.setIdPersona(id);
            personaVO.setNombrePersona(nombre);
            personaVO.setFechaNacimiento(fechaN);
            personaVO.setTelefono(telefono);
            personaVO.setEmail(email);
            perOcupacionVO.setIdOcupacion(ocupacion);
            personaVO.setIdInstitucion(institucion);
            personaVO.setIdFacultad(facultad);
            personaVO.setFechaIngreso(fechaIngreso);
            personaVO.setEstadoActual(estado);
            personaVO.setUsuario(usuario);
            personaVO.setContraseña(contrasenia);

            errorM = personaBO.crearPersona(personaVO, perOcupacionVO, selectedOptions);
            info(errorM);
            
        } catch (Exception ce) {
            error("Error al crear la Persona");
            ce.getStackTrace();
        }

        return "OK";
    }

    public void limpiar() {

        campoIdentificacion.setValue("");
        campoNombrePersona.setValue("");
        fechaNacimiento.setValue("");
        campoTelPersona.setValue("");
        campoEmail.setValue("");
        fechaIngresoPersona.setValue("");
        campoUsr.setValue("");
        campoContraseña.setValue("");
        campoReContraseña.setValue("");

    }

    public String button1_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return "consultarP";
    }

   private boolean esNumericoRegex(String numero){
      Pattern p = Pattern.compile("[0-9]+");
      Matcher m = p.matcher(numero);
      return m.matches();
    }

    private boolean esCadenaRegex(String cadena){
       Pattern p = Pattern.compile("[a-zA-ZáéíóúñÁÉÍÓÚÑ ]+");
       Matcher m = p.matcher(cadena);
       return m.matches();
    }

    private boolean validarCorreoRegex(String correo){
      Pattern p = Pattern.compile("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$");
      Matcher m = p.matcher(correo);
      return m.matches();
    }

    public String buttonCancelarPersona_action() {

        campoIdentificacion.setValue("");
        campoNombrePersona.setValue("");
        fechaNacimiento.setValue("");
        campoTelPersona.setValue("");
        campoEmail.setValue("");
        fechaIngresoPersona.setValue("");
        campoUsr.setValue("");
        campoContraseña.setValue("");
        campoReContraseña.setValue("");
        return null;
    }
}

